package cm.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author: yxh
 * @Description: 枚举实现类
 * @Date: Created in 2023/5/17 13:51
 * @Modified By:
 */
public class EnumValidator implements ConstraintValidator<EnumValid, Object> {

    /**
     * 枚举校验注解
     */
    private EnumValid annotation;

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        boolean result = false;
        Class<?> cls = annotation.target();
        boolean ignoreEmpty = annotation.ignoreEmpty();
        // target为枚举，并且value有值，或者不忽视空值，才进行校验
        if (cls.isEnum() && (Objects.nonNull(value) || !ignoreEmpty)) {
            try {
                Object[] objects = cls.getEnumConstants();
                Method method = cls.getMethod("getCode");
                for (Object obj : objects) {
                    // 使用此注解的枚举类需要重写toString方法，改为需要验证的值
                    if (method.invoke(obj).equals(value)) {
                        result = true;
                        break;
                    }
                }
            }catch (Exception e){
                return false;
            }
        } else {
            result = true;
        }
        return result;
    }
}
